package com.zmx.doctor.view.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.netease.nim.avchatkit.AVChatKit;
import com.netease.nim.avchatkit.model.Accounts;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.avchat.AVChatCallback;
import com.netease.nimlib.sdk.avchat.AVChatManager;
import com.netease.nimlib.sdk.avchat.model.AVChatChannelInfo;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.doctor.BaseActivity;
import com.zmx.doctor.MainActivity;
import com.zmx.doctor.R;
import com.zmx.doctor.adapter.MeetingDoctorAdapter;
import com.zmx.doctor.okhttp.OkHttp3ClientManager;
import com.zmx.doctor.pojo.Meeting;
import com.zmx.doctor.pojo.MeetingDoctor;
import com.zmx.doctor.pojo.MultipartyCallsMessage;
import com.zmx.doctor.utils.AllUtil;
import com.zmx.doctor.view.util.MyDialog;
import com.zmx.doctor.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MeetingDetailsActivity extends BaseActivity {


    @BindView(R.id.title)
    EditText title;
    @BindView(R.id.content)
    EditText content;
    @BindView(R.id.start_date)
    TextView startDate;
    @BindView(R.id.start_time)
    TextView startTime;
    @BindView(R.id.end_date)
    TextView endDate;
    @BindView(R.id.end_time)
    TextView endTime;
    @BindView(R.id.rv_view)
    RecyclerView rvView;
    @BindView(R.id.save)
    Button save;
    private int meeting_id;
    private Meeting meeting;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private SimpleDateFormat sdf_date = new SimpleDateFormat("yyyy/MM/dd");
    private SimpleDateFormat sdf_time = new SimpleDateFormat("HH:mm");


    private String end_date = "";
    private String end_time = "";
    private String start_date = "";
    private String start_time = "";

    private Calendar calendar = Calendar.getInstance(Locale.CHINA);

    private MeetingDoctorAdapter adapter;
    private List<MeetingDoctor> lists;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_meeting_details;
    }

    @Override
    protected void initViews() {

        setToolbar(R.id.tool_bar);
        ButterKnife.bind(this);

        meeting_id = getIntent().getIntExtra("meeting_id", 0);

        lists = new ArrayList<>();
        adapter = new MeetingDoctorAdapter(mActivity, lists);
        rvView.setLayoutManager(new GridLayoutManager(mActivity, 5));
        rvView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                if (lists.get(listPosition).getMeeting_id() == 0) {

                    Bundle bundle = new Bundle();
                    bundle.putInt("meeting_id", meeting_id);
                    startActivity(AddMeetingDoctorActivity.class, bundle);

                } else {

                    AlertDialog alertDialog = new AlertDialog.Builder(mActivity)
                            .setTitle("是否移除该成员")
                            .setMessage("是否移除该成员")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    setMeetingUser(lists.get(listPosition).getJoin_member_id()+"");
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    return;
                                }
                            }).create();
                    alertDialog.show();

                }

            }
        });


        meetingMember();
        meetingDetails(meeting_id + "");

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        meetingMember();
        meetingDetails(meeting_id + "");

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        Gson gson = new Gson();
                        meeting = gson.fromJson(object.getString("data"), Meeting.class);
                        title.setText(meeting.getTitle());
                        content.setText(meeting.getTitle());
                        try {

                            startDate.setText(sdf_date.format(sdf.parse(meeting.getAddtime())));
                            start_date = startDate.getText().toString();
                            startTime.setText(sdf_time.format(sdf.parse(meeting.getAddtime())));
                            start_time = startTime.getText().toString();
                            endDate.setText(sdf_date.format(sdf.parse(meeting.getEndtime())));
                            end_date = endDate.getText().toString();
                            endTime.setText(sdf_time.format(sdf.parse(meeting.getEndtime())));
                            end_time = endTime.getText().toString();

                        } catch (ParseException e) {
                            e.printStackTrace();
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 2:
                    try {

                        lists.clear();
                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONArray data = object.getJSONArray("data");
                        Gson gson = new Gson();
                        for (int i = 0; i < data.length(); i++) {

                            MeetingDoctor md = gson.fromJson(data.getJSONObject(i).toString(), MeetingDoctor.class);
                            lists.add(md);

                        }

                        //添加按钮
                        MeetingDoctor add = new MeetingDoctor();
                        add.setMeeting_id(0);
                        lists.add(add);

                        adapter.setListAndNotifyDataSetChanged(lists);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 3:

                    String meeting_id = msg.obj.toString();

                    View view = getLayoutInflater().inflate(R.layout.dialog, null);

                    MyDialog mMyDialog = new MyDialog(mActivity, 0, 0, view, R.style.DialogTheme);
                    mMyDialog.setCancelable(true);
                    mMyDialog.show();
                    Button cancel = view.findViewById(R.id.cancel);
                    cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            mMyDialog.dismiss();
                        }
                    });
                    Button add = view.findViewById(R.id.add);
                    add.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            userAddMeeting(meeting_id);
                            mMyDialog.dismiss();
                        }
                    });

                    break;

                case 4:
                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 5:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Gson gson = new Gson();
                        Log.e("id", "见附件" + object.toString());
                        Toast(object.getString("msg"));

                        if (object.getInt("code") == 1) {

                            JSONObject data = object.getJSONObject("data");

                            ArrayList<Accounts> as = new ArrayList<>();
                            ArrayList<String> message = new ArrayList<>();

                            JSONArray array = data.getJSONArray("accid");

                            for (int i = 0; i < array.length(); i++) {

                                Log.e("id", "见附件" + array.get(i).toString());
                                Accounts accounts = gson.fromJson(array.get(i).toString(),Accounts.class);
                                as.add(accounts);
                                message.add(accounts.getJoin_member_id());

                            }

                            int roomID = data.getInt("meeting_id");

                            MultipartyCallsMessage mcm = new MultipartyCallsMessage();
                            mcm.setRoomID(roomID + "");
                            mcm.setAccounts(as);
                            String mcm_message = gson.toJson(mcm);


                            AVChatManager.getInstance().createRoom(roomID + "", "家属", new AVChatCallback<AVChatChannelInfo>() {
                                @Override
                                public void onSuccess(AVChatChannelInfo avChatChannelInfo) {

                                    Log.e("成功", "成功");

                                    for (String s : message) {

                                        Log.e("成功", "成功" + s);

                                        // 以单聊类型为例
                                        SessionTypeEnum sessionType = SessionTypeEnum.P2P;
                                        // 创建一个文本消息
                                        IMMessage textMessage = MessageBuilder.createTextMessage(s, sessionType, mcm_message);
                                        // 发送给对方
                                        NIMClient.getService(MsgService.class).sendMessage(textMessage, false);

                                    }

                                    AVChatKit.outgoingTeamCall(mActivity,1, true, "1", roomID + "", as, "多方通话");

                                }

                                @Override
                                public void onFailed(int code) {

                                    Log.e("错误码", "错误码" + code);

                                    AVChatKit.outgoingTeamCall(mActivity,1, true, "1", roomID + "", as, "多方通话");

                                }

                                @Override
                                public void onException(Throwable exception) {

                                    Log.e("错误提示", "错误提示" + exception.toString());

                                }
                            });

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;

                case 6:
                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));
                        if (object.getInt("code") == 1){

                            meetingMember();

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

            }

        }
    };


    /**
     * 日期选择
     *
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar, int logo) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "/" + (monthOfYear + 1) + "/" + dayOfMonth);

                if (logo == 1) {

                    start_date = tv.getText().toString();

                } else {
                    end_date = tv.getText().toString();
                }

            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

    /**
     * 时间选择
     *
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public void showTimePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar, int logo) {
        // Calendar c = Calendar.getInstance();
        // 创建一个TimePickerDialog实例，并把它显示出来
        // 解释一哈，Activity是context的子类
        new TimePickerDialog(activity, themeResId,
                // 绑定监听器
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tv.setText(hourOfDay + ":" + minute);
                        if (logo == 1) {

                            start_time = tv.getText().toString();

                        } else {
                            end_time = tv.getText().toString();
                        }
                    }
                }
                // 设置初始时间
                , calendar.get(Calendar.HOUR_OF_DAY)
                , calendar.get(Calendar.MINUTE)
                // true表示采用24小时制
                , true).show();
    }


    @OnClick({R.id.start_date, R.id.start_time, R.id.end_date, R.id.end_time, R.id.save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.start_date:
                showDatePickerDialog(this, 4, startDate, calendar, 1);
                break;
            case R.id.start_time:
                showTimePickerDialog(this, 4, startTime, calendar, 1);
                break;
            case R.id.end_date:
                showDatePickerDialog(this, 4, endDate, calendar, 2);
                break;
            case R.id.end_time:
                showTimePickerDialog(this, 4, endTime, calendar, 2);
                break;
            case R.id.save:

                if (end_date.equals("")) {
                    Toast("请选择结束日期");
                    return;
                }

                if (end_time.equals("")) {
                    Toast("请选择结束时间");
                    return;
                }
                if (start_date.equals("")) {
                    Toast("请选择开始日期");
                    return;
                }
                if (start_time.equals("")) {
                    Toast("请选择开始时间");
                    return;
                }
                if (content.getText().toString().equals("")) {
                    Toast("请输入内容");
                    return;
                }
                if (title.getText().toString().equals("")) {
                    Toast("请输入内容");
                    return;
                }
                editMeeting();

                break;
        }
    }

    public void editMeeting() {

        Random rd = new Random();
        String room = rd.nextInt(1000) + "";

        List<String> ls = new ArrayList<>();
        ls.add(start_date + " " + start_time);
        ls.add(content.getText().toString());
        ls.add(end_date + " " + end_time);
        ls.add(meeting_id + "");
        ls.add(room);
        ls.add(title.getText().toString());
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "editMeeting");
        params.put("data[room]", room);
        params.put("data[meeting_id]", meeting_id);
        params.put("data[title]", title.getText().toString());
        params.put("data[content]", content.getText().toString());
        params.put("data[addtime]", start_date + " " + start_time);
        params.put("data[endtime]", end_date + " " + end_time);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/doctor/", params, handler, 4, 404);

    }


    public void userAddMeeting(String meeting_id) {

        List<String> ls = new ArrayList<>();
        ls.add(meeting_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "userAddMeeting");
        params.put("data[meeting_id]", meeting_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/doctor/", params, handler, 5, 404);

    }

    public void meetingDetails(String meeting_id) {

        List<String> ls = new ArrayList<>();
        ls.add(meeting_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "meetingDetails");
        params.put("data[meeting_id]", meeting_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/doctor/", params, handler, 1, 404);

    }


    public void meetingMember() {

        List<String> ls = new ArrayList<>();
        ls.add(meeting_id+"");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "meetingMember");
        params.put("data[meeting_id]", meeting_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/doctor/", params, handler, 2, 404);

    }

    public void setMeetingUser(String join_member_id) {

        List<String> ls = new ArrayList<>();
        ls.add(join_member_id);
        ls.add(meeting_id + "");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "setMeetingUser");
        params.put("data[join_member_id]", join_member_id);
        params.put("data[meeting_id]", meeting_id + "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/doctor/", params, handler, 6, 404);

    }

}
